//
//  LFTMCTeamMemberCardViewController.m
//  lofter-mvpcourse-ios
//
//  Created by Thomas Quan on 2017/5/5.
//  Copyright © 2017年 undefined-zola. All rights reserved.
//

#import "LFTMCTeamMemberCardViewController.h"
#import "NIMCommonTableData.h"
#import "NIMCommonTableDelegate.h"
#import "NIMAvatarImageView.h"
#import "NIMCardMemberItem.h"
#import "NIMUsrInfoData.h"
#import "NIMKitUtil.h"
#import "UIView+Toast.h"
#import "NIMKit.h"
#import "UIView+NIM.h"
#import "NIMKitColorButtonCell.h"
#import "NIMKitSwitcherCell.h"
#import "Masonry.h"
#import "NIMGlobalMacro.h"
#import "UIButton+LFTMCBlock.h"

@interface LFTMCUserInfoView : UIView

@property (nonatomic, strong) NIMUsrInfo *usrInfo;

@property (nonatomic, strong) NIMUserInfo *userInfo;

@property (nonatomic, strong) NIMAvatarImageView *avatarView;

@property (nonatomic, strong) UILabel *nickLabel;

//@property (nonatomic, strong) UILabel *emailLabel;

@end

@implementation LFTMCUserInfoView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.avatarView];
        [self addSubview:self.nickLabel];
//        [self addSubview:self.emailLabel];
    }
    return self;
}

- (void)refreshData {
    NSURL *avatarURL;
    if (self.usrInfo.info.avatarUrlString) {
        avatarURL = [NSURL URLWithString:self.usrInfo.info.avatarUrlString];
    }
    [self.avatarView nim_setImageWithURL:avatarURL placeholderImage:self.usrInfo.info.avatarImage];
    
    self.nickLabel.text = self.userInfo.nickName;
//    self.emailLabel.text = [NSString stringWithFormat:@"账号：%@", self.userInfo.email];
    [self.nickLabel sizeToFit];
//    [self.emailLabel sizeToFit];
    self.userInteractionEnabled = NO;
}

- (NIMAvatarImageView *)avatarView
{
    if (!_avatarView) {
        _avatarView = [[NIMAvatarImageView alloc] initWithFrame:CGRectMake(142, 95, 90, 90)];
        _avatarView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    }
    return _avatarView;
}

- (UILabel *)nickLabel
{
    if (!_nickLabel) {
        _nickLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _nickLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
        _nickLabel.font = [UIFont systemFontOfSize:20];
        _nickLabel.textColor = NIMKit_UIColorFromRGB(0x333333);
    }
    return _nickLabel;
}

//- (UILabel *)emailLabel {
//    if (!_emailLabel) {
//        _emailLabel = [[UILabel alloc] initWithFrame:CGRectZero];
//        _emailLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin |
//        UIViewAutoresizingFlexibleRightMargin;
//        _emailLabel.font = [UIFont systemFontOfSize:15];
//        _emailLabel.textColor = NIMKit_UIColorFromRGB(0x999999);
//    }
//    return _emailLabel;
//}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.avatarView.nim_top = 30.f;
    self.avatarView.nim_centerX = self.nim_width * .5f;
    
    self.nickLabel.nim_centerX = self.avatarView.nim_centerX;
    self.nickLabel.nim_top = self.avatarView.nim_bottom + 25;
    
//    self.emailLabel.nim_centerX = self.avatarView.nim_centerX;
//    self.emailLabel.nim_top = self.nickLabel.nim_bottom + 5;
}

@end

@interface LFTMCMuteBar : UIView

@property (nonatomic, strong) UISwitch *switcher;

@property (nonatomic, strong) UILabel *textLabel;

@property (nonatomic, copy) NSString *userId;

@property (nonatomic, copy) NSString *teamId;

@end

@implementation LFTMCMuteBar

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.switcher];
        [self addSubview:self.textLabel];
    }
    return self;
}

- (void)refreshData:(NSString *)userId teamId:(NSString *)teamId{
    self.userId = userId;
    self.teamId = teamId;
    
    self.textLabel.text       = @"禁言";
    NIMTeamMember *member = [[NIMSDK sharedSDK].teamManager teamMember:userId inTeam:teamId];
    NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:teamId];
    BOOL isMuted = member.isMuted;
    [self.switcher setOn:isMuted animated:NO];
    if (team.inAllMuteMode) {
        self.switcher.enabled = NO;
    }
    [self.textLabel sizeToFit];
}

- (UISwitch *)switcher {
    if (!_switcher) {
        _switcher = [[UISwitch alloc] initWithFrame:CGRectZero];
        [_switcher addTarget:self action:@selector(updateMute:) forControlEvents:UIControlEventValueChanged];
    }
    return _switcher;
}

- (UILabel *)textLabel {
    if (!_textLabel) {
        _textLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _textLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin |
        UIViewAutoresizingFlexibleRightMargin;
        _textLabel.font = [UIFont systemFontOfSize:17];
        _textLabel.textColor = NIMKit_UIColorFromRGB(0x333333);
    }
    return _textLabel;
}

#define SwitcherRight 15
- (void)layoutSubviews{
    [super layoutSubviews];
    self.textLabel.nim_left = 15;
    self.textLabel.nim_centerY = self.nim_height * .5f;
    self.switcher.nim_right   = self.nim_width - SwitcherRight;
    self.switcher.nim_centerY = self.nim_height * .5f;
}

- (void)updateMute:(UISwitch *)switcher
{
    __block typeof(self) wself = self;
    BOOL mute = switcher.on;
    
    [[LFTMCUtil sharedInstance].dataSource lftmc_trackEventID:@"IMUserGag"
                                                     category:nil
                                                        label:mute ? @"ON" : @"OFF"
                                                   attributes:nil];
    
    [[NIMSDK sharedSDK].teamManager updateMuteState:mute userId:self.userId inTeam:self.teamId completion:^(NSError *error) {
        if (!error) {
            NSString *hintText = switcher.on ? @"禁言成功" : @"取消禁言成功";
            [self makeToast:hintText];
//            switcher.on = !mute;
        } else {
            NSString *hintText = switcher.on ? @"禁言失败" : @"取消禁言失败";
            [self makeToast:hintText];
//            [switcher setOn:!mute animated:YES];
        }
    }];
}


@end


@interface LFTMCTeamMemberCardViewController ()

@property (strong, nonatomic) UITableView *tableView;

@property (strong, nonatomic) NIMUsrInfo *usrInfo;

@property (strong, nonatomic) NIMUserInfo *userInfo;

@property (nonatomic,strong) NIMCommonTableDelegate *delegator;

@property (nonatomic,strong) NSArray *data;

@property (nonatomic, copy) NSString *userId;

@property (nonatomic, copy) NSString *teamId;

@end

@implementation LFTMCTeamMemberCardViewController

- (instancetype)initWithUserId:(NSString *)userId team:(NSString *)teamId{
    self = [super initWithNibName:nil bundle:nil];
    if(self) {
        self.userId = userId;
        self.teamId = teamId;
        _member = [[NIMTeamCardMemberItem alloc] initWithMember:[[NIMSDK sharedSDK].teamManager teamMember:userId inTeam:teamId]];
        _viewer = [[NIMTeamCardMemberItem alloc] initWithMember:[[NIMSDK sharedSDK].teamManager teamMember:[NIMSDK sharedSDK].loginManager.currentAccount inTeam:teamId]];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNav];
    NIMUsrInfo *user = [[NIMUsrInfo alloc] init];
    user.info = [[NIMKit sharedKit] infoByUser:self.member.memberId option:nil];
    self.usrInfo = user;
    NIMUser *u = [[NIMSDK sharedSDK].userManager userInfo:self.member.memberId];
    self.userInfo = u.userInfo;
    
    self.view.backgroundColor = NIMKit_UIColorFromRGB(0xF6F6F6);
    self.navigationItem.title = @"个人名片";
    
    LFTMCUserInfoView *userInfoView = [[LFTMCUserInfoView alloc] initWithFrame:CGRectMake(0, 66, self.view.frame.size.width, 225)];
    userInfoView.userInfo = self.userInfo;
    userInfoView.usrInfo = self.usrInfo;
    [userInfoView refreshData];
    
    //自己是管理员，对方不是管理员，对方不是自己
    [self.view addSubview:userInfoView];
    BOOL isIManager = [self isOwnerOrManager:_viewer];
    BOOL isHeManager = [self isOwnerOrManager:_member];
    BOOL isMe = [self isSelf];
    
        
    LFTMCUtil *util = [LFTMCUtil sharedInstance];
    LFTMCIdentity identity = [util identityFor:_member.memberId inSession:util.teamModel.teamId];
    NSString *eventId = @"PortraitClick";
    NSString *label;
    if (identity == LFTMCIdentityAssistans) {
        label = @"Assistant";
    } else if (identity == LFTMCIdentityTeacher){
        label = @"Lecturer";
    } else if (identity == LFTMCIdentityManager) {
        label = @"Admin";
    } else  {
        label = nil;
        eventId = @"UserPortraitClick";
    }
    
    [util.dataSource lftmc_trackEventID:eventId
                               category:nil
                                  label:label
                             attributes:nil];
    
    
    
    
    if (isIManager && !isHeManager && !isMe) {
        LFTMCMuteBar *muteBar = [[LFTMCMuteBar alloc] initWithFrame:CGRectMake(0, 66+20+userInfoView.frame.size.height, self.view.frame.size.width, 50)];
        [muteBar refreshData:self.member.member.userId teamId:self.member.member.teamId];
        [self.view addSubview:muteBar];
    }
    
}

- (void)close {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupNav {
    UIBarButtonItem *backButtonItem =
    [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"LFTMC_Back"]
                                     style:UIBarButtonItemStylePlain
                                    target:self
                                    action:@selector(close)];
    [backButtonItem setTintColor:NIMKit_UIColorFromRGB(0x333333)];
    self.navigationItem.leftBarButtonItem = backButtonItem;
}

#pragma mark - Private

- (BOOL)isSelf
{
    return [self.viewer.memberId isEqualToString:self.member.memberId];
}

- (BOOL)isOwner
{
    return self.viewer.member.type == NIMTeamMemberTypeOwner;
}

- (BOOL)isOwnerOrManager:(NIMTeamCardMemberItem *)member {
    return
    member.member.type == NIMTeamMemberTypeOwner ||
    member.member.type == NIMTeamMemberTypeManager;
}

- (BOOL)canUpdateTeamMember
{
    BOOL viewerIsOwner   = [self isOwner];
    BOOL viewerIsManager = self.viewer.member.type == NIMTeamMemberTypeManager;
    BOOL memberIsNormal  = self.member.member.type == NIMTeamMemberTypeNormal;
    if (viewerIsOwner) {
        return ![self isSelf];
    }
    if (viewerIsManager) {
        return memberIsNormal;
    }
    return NO;
}

@end
